import {
	defineStore
} from 'pinia';

import {
	showConfirmDialog
} from "../hooks/useConfirm.js"

const USER_INFO = "USER_INFO";
const USER_TOKEN = "USER_TOKEN";

export const useUserStore = defineStore('userStore', {
	state: () => {
		const defaultUser = uni.getStorageSync(USER_INFO) || {
			id: "",
			name: "",
			mobile: "",
			role: "",
		};

		const defaultToken = uni.getStorageSync(USER_TOKEN);

		return {
			// _token: defaultToken,
			token: defaultToken,
			id: defaultUser.id,
			name: defaultUser.name,
			mobile: defaultUser.mobile,
			role: defaultUser.role,
		}
	},
	getters: {
		// token() {
		// 	console.log(111);
		// 	if (this._token) return this._token;
		// 	const token = uni.getStorageSync(USER_TOKEN);
		// 	if (token) {
		// 		this._token = token;
		// 		return token;
		// 	}

		// 	showConfirmDialog({
		// 		title: "未登录",
		// 		content: "您还没有登录，请先登录"
		// 	});

		// 	uni.reLaunch({
		// 		url: "/pages/login/login"
		// 	});
		// }



		normal() {
			return this.role === "normal";
		},
		normalAdmin() {
			return ['normal', 'admin'].includes(this.role);
		},
		admin() {
			return this.role === "admin";
		},
		notAdmin() {
			return this.role !== "admin";
		}

	},
	actions: {
		setToken(token) {
			this.token = token;
			uni.setStorageSync(USER_TOKEN, token);
		},
		setUser(user) {
			const {
				id,
				name,
				mobile,
				role
			} = user;
			this.id = id;
			this.name = name;
			this.mobile = mobile;
			this.role = role;

			uni.setStorageSync(USER_INFO, user);
		},
		logout() {
			this.$reset();
			uni.clearStorage();
		},
		guestLogin() {
			this.token = "none";
			this.id = 0;
			this.name = "游客用户";
			this.mobile = "无手机号";
			this.role = "guest";
		}
	}
});